<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitepagebadge
 * @copyright  Copyright 2010-2011 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: Badges.php 2011-05-05 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitepagebadge_Model_DbTable_Badges extends Engine_Db_Table {
	
	protected $_rowClass = "Sitepagebadge_Model_Badge";
	
	/**
	 * Return badge data
	 *
	 * @param Int page_id
	 * @return Zend_Db_Table_Select
	 */
	public function getBadgesData($params = array()) {
		
		$badgeTableName = $this->info ( 'name' );
		
		if (isset ( $params ['popular_badges'] ) && ! empty ( $params ['popular_badges'] )) {
			$total_sitepagebadges = Engine_Api::_ ()->getApi ( 'settings', 'core' )->sitepagebadge_popular_widgets;
			
			$pageTableName = Engine_Api::_ ()->getDbTable ( 'pages', 'sitepage' )->info ( 'name' );
			
			$select = $this->select ()->setIntegrityCheck ( false )->from ( $badgeTableName )->joinLeft ( $pageTableName, "$pageTableName.badge_id = $badgeTableName.badge_id", array ('COUNT(engine4_sitepage_pages.badge_id) AS Frequency' ) )->group ( $pageTableName . '.badge_id' )->order ( 'Frequency DESC' )->order ( $badgeTableName . '.creation_date DESC' )->limit ( $total_sitepagebadges );
			
			$select = $select->where ( $pageTableName . '.search = ?', '1' )->where ( $pageTableName . '.closed = ?', '0' )->where ( $pageTableName . '.approved = ?', '1' )->where ( $pageTableName . '.declined = ?', '0' )->where ( $pageTableName . '.draft = ?', '1' );
			if (Engine_Api::_ ()->sitepage ()->hasPackageEnable ()) {
				$select->where ( $pageTableName . '.expiration_date  > ?', date ( "Y-m-d H:i:s" ) );
			}
			
			return $this->fetchAll ( $select );
		
		} else {
			//MAKE QUERY
			$select = $this->select ()->order ( 'creation_date DESC' );
			
			if (isset ( $params ['search_code'] ) && ! empty ( $params ['search_code'] )) {
				$select->from ( $badgeTableName, array ('badge_id', 'title' ) );
			}
			
			//FETCH RESULTS
			return $this->fetchAll ( $select );
		}
	}

}
?>